/**
 * <p>Package : org.tea.springdata.service</p>
 * <p>E-Mail : ztlyde@gmail.com</p>
 */
package org.tea.springdata.jpa.service.impl;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.tea.springdata.jpa.dao.IUserDao;
import org.tea.springdata.jpa.domain.User;

/**
 * @Author: 张廷
 * @Description: 类描述
 * @Date: 2012-6-29
 * @Time: 下午5:34:04
 */
@Service("userService")
public class UserService {
	
	@Autowired
	private IUserDao dao;
	
	@PersistenceContext(unitName = "spring_data_jpa")
	private EntityManager em;
	
	public void save(User user) {
		dao.save(user);
	}

	public void delete(Long id) {
		dao.delete(id);
	}

	public void update(User user) {
		dao.saveAndFlush(user);
	}

	public List<User> findAll() {
		return dao.findAll();
	}
	
	public User findSingle(Serializable id) {
		return em.find(User.class, id);
	}
	
	public List<User> listQuery(String queryString) {
		TypedQuery<User> query = em.createQuery(queryString, User.class);
		return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<User> findAllByNamedQuery(String name) {
		Query query = em.createNamedQuery("findAllUserWithName").setParameter("name", "%" + name + "%");
		return query.getResultList();
	}

	public List<User> findUserWithParamIndex(String name) {
		return dao.findUserWithParamIndex(name);
	}
	
	public List<User> findUserWithParamName(String name) {
		return dao.findUserWithParamName(name);
	}
	
	public Page<User> findByPaginate(Pageable pageable) {
		return dao.findAll(pageable);
	}
	
	public int updateFixedNameById(Long id, String name) {
		return dao.updateFixedNameById(id, name);
	}
	
	public Page<User> findBySpecAndPaginate(Pageable pageable) {
		return dao.findAll(new Specification<User>(){
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// root = query.from(User.class);
				Path<String> nameExp = root.get("name");
				return cb.like(nameExp, "%Sam%");
			}
			
		}, pageable);
	}
	
	public Page<User> listPageByName(String name, Pageable pageable) {
		return dao.listPageByName(name, pageable);
	}
	
}
